# export network by module

# Rscript step6.R --exprFile "../test_data/datExpr.csv" --TOM "../1_construct_network/TOM.RData" --annotFile "../test_data/annot.csv" --moduleName "brown" --network "../1_construct_network/network.RData" --output "../6_export_network"

library(optparse)


option_list = list(
  make_option("--exprFile", type="character", default=NULL,
              help="expression file path"),
  make_option("--network", type="character", default=NULL,
              help="network file path"),
  make_option("--TOM", type="character", default=NULL,
              help="TOM file path"),
  make_option("--annotFile", type="character", default=NULL,
              help="annotation file path"),
  make_option("--moduleName", type="character", default=NULL,
              help="module name"),
  make_option("--topNum", type="integer", default=30,
              help="top number [default= %default]"),
  make_option("--output", type="character", default="out.txt",
              help="output path [default= %default]")
)

# 解析命令行参数
opt_parser = OptionParser(option_list=option_list, add_help_option=TRUE)
opts = parse_args(opt_parser)

datExpr = read.csv(opts$exprFile, stringsAsFactors = FALSE, row.names = 1);
datAnnot = read.csv(opts$annotFile, stringsAsFactors = FALSE);

load(opts$network)
load(opts$TOM)

library(WGCNA)

moduleColors = labels2colors(net$colors)

# export network data
probes = names(datExpr)
inModule = (moduleColors==opts$moduleName);
modProbes = probes[inModule];
modGenes = datAnnot$gene_symbol[match(modProbes, datAnnot$gene_id)];
# Select the corresponding Topological Overlap
modTOM = TOM[inModule, inModule];
dimnames(modTOM) = list(modProbes, modProbes)

IMConn = softConnectivity(datExpr[, modProbes]);
top = (rank(-IMConn) <= opts$topNum)
vis = exportNetworkToVisANT(
  modTOM[top, top],
  file = paste(opts$output, paste(opts$moduleName, "_network.txt"), sep="/"),
  weighted = TRUE,
  threshold = 0,
  probeToGene = data.frame(datAnnot$gene_id, datAnnot$gene_symbol)
)
